﻿using Newtonsoft.Json;

using System.Threading.Tasks;

using Utils;

namespace System.Net.Http
{
    public static class HttpClientExtensions
    {

        /// <summary>
        /// 转为json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content"></param>
        /// <param name="catchResult">抓取错误</param>
        /// <returns></returns>
        public static async Task<T> ReadAsJsonResult<T>(this HttpContent content, Func<HttpContent, Task<T>> catchResult = null, JsonSerializerSettings jsonSerializerSettings = null)
        {
            if (catchResult != null)
            {
                return await catchResult.Invoke(content);
            }
            string result = await content.ReadAsStringAsync();
            if (string.IsNullOrEmpty(result))
            {
                return default;
            }
            return JsonConvert.DeserializeObject<T>(result, jsonSerializerSettings);
        }
        /// <summary>
        /// 获取 json 序列化结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="taskHttpResponseMessage"></param>
        /// <param name="resultFilter"></param>
        /// <returns></returns>
        public static async Task<T> JsonResultAsync<T>(this Task<HttpResponseMessage> taskHttpResponseMessage, Func<HttpResponseMessage, Task<T>> resultFilter = null, JsonSerializerSettings jsonSerializerSettings = null)
        {
            var httpResponseMessage = await taskHttpResponseMessage;
            return await httpResponseMessage.JsonResultAsync<T>(resultFilter, jsonSerializerSettings);
        }

        /// <summary>
        /// 获取 json 序列化结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="httpResponseMessage"></param>
        /// <param name="resultFilter"></param>
        /// <returns></returns>
        public static async Task<T> JsonResultAsync<T>(this HttpResponseMessage httpResponseMessage, Func<HttpResponseMessage, Task<T>> resultFilter = null, JsonSerializerSettings jsonSerializerSettings = null)
        {
            if (resultFilter != null)
            {
                return await resultFilter(httpResponseMessage);
            }
            return await httpResponseMessage.Content.ReadAsJsonResult<T>();
        }



        public static string AppendQuery(this string url, object query)
        {
            var urlParams = query?.ToDictionary();
            if (urlParams == null) return url;
            url += url.Contains("?") ? "&" : "?";
            url += urlParams.ToUrlQuery();
            return url;
        }


    }
}
